package com.leyou.sms.mq;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.utils.SmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class ListenMessage {

    @Autowired
    private SmsUtil smsUtil;

    /**
     * 发送短信验证码的监听器
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.Queue.SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = MQConstants.Exchange.SMS_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKey.VERIFY_CODE_KEY
    ))
    public void listenVerifyCodeMessage(Map<String,String> msg){
        if(CollectionUtils.isEmpty(msg)){
            // msg为空，结束
            return;
        }
        // 获取手机号
        String phone = msg.get("phone");
        if(!RegexUtils.isPhone(phone)){
            // 手机号有误，结束
            log.error("取消短信发送，手机号格式不正确：{}", phone);
            return;
        }
        // 获取验证码
        String code = msg.get("code");
        if(!RegexUtils.isValidCode(code)){
            // 验证码有误，结束
            log.error("取消短信发送，验证码格式不正确：{}", code);
            return;
        }
        smsUtil.sendVerifyCode(phone, code);
    }
}
